"""
handle message for team-related operations
"""

import json


async def send_msg_to_team(db, logger, ws_manager, data: dict):
    """
    data: {
        "team_id": int, 发送到的团队id
        "context_type": str, 发送的内容类型(text, file)
        "context": None, 发送的内容(str, dict)
        "source": str, 发送者的mac_addr
    }
    """
    try:
        # 获取团队信息
        team_info = db.get_one("Team", {"id": data.get("team_id")})
        # 获取团队成员
        team_members = db.execute_query(
            """
            SELECT ut.*,
            u.name as user_name,
            u.mac_addr as user_mac_addr,
            u.socket_id as user_socket_id,
            u.status as user_status
            FROM User_Team ut
            JOIN User u ON ut.user_id = u.id
            WHERE ut.team_id = ?
            """,
            (data.get("team_id"),),
        )

        # 获取发送者信息
        source_user = db.get_one("User", {"mac_addr": data.get("source")})
        if not source_user:
            raise ValueError(f"Source user {data.get('source')} does not exist.")

        tm_id = None
        # 保存消息到数据库
        if data.get("context_type") == "text":
            tm_id = db.insert_one(
                "Team_Message",
                {
                    "team_id": data.get("team_id"),
                    "user_id": source_user["id"],
                    "context": data.get("context"),
                },
            )
        elif data.get("context_type") == "file":
            tm_id = db.insert_one(
                "Team_Message",
                {
                    "team_id": data.get("team_id"),
                    "user_id": source_user["id"],
                    "context": "File",
                    "file_id": data.get("context", {}).get("file_id"),
                },
            )
        else:
            raise Exception("未知的消息类型")

        # 构建消息内容
        message_content = {
            "category": "team_message",
            "source": data.get("source"),
            "source_name": source_user.get("name"),
            "team_id": data.get("team_id"),
            "team_name": team_info["name"],
            "context_type": data.get("context_type", "text"),
            "context": data.get("context"),
            "message_id": tm_id,
        }

        # 发送消息给所有在线成员(除自己外)
        for member in team_members:
            if member and member.get("user_id") != source_user.get("id"):
                if member.get("user_socket_id") in ws_manager.active_connections:
                    websocket = ws_manager.active_connections[member["user_socket_id"]]
                    await ws_manager.send2client(json.dumps(message_content, ensure_ascii=False), websocket)

        # 添加已读信息
        db.insert_one(
            "Team_Message_Read",
            {
                "team_message_id": tm_id,
                "user_id": source_user["id"],
                "team_id": data["team_id"],
            },
        )
    except Exception as e:
        raise e


def get_team_message(db, logger, data: dict):
    """
    获取团队消息 (默认获取全部)

    Args:
        db (_type_): _description_
        logger (_type_): _description_
        data (dict): 包括获取者的mac_addr, team_id,
    """

    try:
        user_info = db.get_one("user", {"mac_addr": data.get("mac_addr")})
        # 获取Team message （关联用户信息）

        sql = f"""
        SELECT tm.*, f.origin_name as file_origin_name, 
        f.filename as file_name, f.size as file_size, 
        f.origin_path as file_origin_path, 
        u.name as sender_name, u.mac_addr as sender_mac
        FROM Team_Message tm
        JOIN User u ON tm.user_id = u.id
        LEFT JOIN File f ON tm.file_id = f.id
        WHERE tm.team_id = ?
        ORDER BY tm.created_at ASC
        """
        team_messages = db.execute_query(sql, (data.get("team_id"),))

        # 添加已读信息（避免重复）
        if team_messages:
            # 准备已读记录数据
            read_records = []
            for message in team_messages:
                # 检查是否已经标记为已读，避免重复
                existing_read = db.get_one(
                    "Team_Message_Read",
                    {
                        "team_message_id": message["id"],
                        "user_id": user_info["id"],
                    },
                )

                # 如果尚未标记为已读，则添加到待插入列表
                if not existing_read:
                    read_records.append(
                        {"team_message_id": message["id"], "user_id": user_info["id"], "team_id": data["team_id"]}
                    )

            # 批量插入已读记录
            if read_records:
                db.insert_many("Team_Message_Read", read_records)

        return team_messages
    except Exception as e:
        raise e


def team_message_readed(db, logger, request):
    try:
        user_info = db.get_one("user", {"mac_addr": request.mac_addr})
        team_info = db.get_one("team", {"id": request.team_id})
        team_messasge_info = db.get_one("Team_Message", {"id": request.msg_id})

        if user_info and team_info and team_messasge_info:
            id = db.insert_one(
                "Team_Message_Read",
                {
                    "team_message_id": team_messasge_info["id"],
                    "user_id": user_info["id"],
                    "team_id": team_info["id"],
                },
            )
            return {"team_message_id": id}
        else:
            raise ValueError("Invalid request")
    except Exception as e:
        raise e
